<template>
  <div>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      class="dataForm"
    >
      <el-row>
        <el-col :span="8">
          <span style="display: none;">目录不存在时是否自动创建: {{ autoCreate }}<br>文件导入方式: {{ fileCheck }}<br>uuid: {{ autoUuid }}</span>
          <el-form-item :label="$t('文件上传')" :rules="[{ required: true}]">
            <!-- 目录上传 -->
            <uploader
              ref="uploader"
              :options="options"
              class="uploader-example"
              :file-status-text="fileStatusText"
              :auto-start="true"
              @file-added="onFileAdded"
              @files-added="onFilesAdded"
              @file-progress="onFileProgress"
              @file-error="errorUpload"
              @file-success="successUpload"
              @file-complete="fileComplete"
            >
              <uploader-drop id="global-uploader-btn">
                <uploader-btn :directory="true"><span>{{ $t('上传文件夹') }}</span></uploader-btn>
              </uploader-drop>
              <uploader-list />
            </uploader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('错误信息')">
            <div :style="{ height: (errorTextHeight - 20) + 'px', overflow: 'auto', 'white-space': 'nowrap' }" v-html="showErrorFileText" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('成功信息')">
            <div :style="{ height: (errorTextHeight - 20) + 'px', overflow: 'auto', 'white-space': 'nowrap' }" v-html="showSuccessFileText" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { config } from '@/utils'
import { getToken } from '@/utils/auth'
import { getVarParam } from '@/api/file/fileBase'
import { ACCEPT_CONFIG } from '@/utils/config'
export default {
  components: {},
  props: {
    errorTextHeight: {
      type: Number,
      default: 400
    },
    fileCheck: {
      type: String,
      default: () => 'TG'
    },
    autoCreate: {
      type: String,
      default: () => 'false'
    }
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      form: {},
      rules: {},
      options: {
        target: config.baseURL + '/init/file/uploadFolderDoc?type=' + this.fileCheck,
        singleFile: false,
        chunkSize: '2048000',
        fileParameterName: 'file',
        // 最大自动失败重试上限
        maxChunkRetries: 3,
        // 并发数
        simultaneousUploads: 1,
        progressCallbacksInterval: 2000,
        speedSmoothingFactor: 0.2,
        testChunks: true, // 是否开启服务器分片校验
        // 服务器分片校验函数，秒传及断点续传基础
        checkChunkUploadedByResponse: function(chunk, message) {
          const objMessage = JSON.parse(message)
          if (objMessage.skipUpload) {
            return true
          }
          return (objMessage.uploaded || []).indexOf(chunk.offset + 1) >= 0
        },
        headers: {
          Authorization: getToken(),
          'auto-create': this.autoCreate,
          'file-check': this.fileCheck,
          'auto-uuid': this.autoUuid
        },
        query: (file, chunk) => {
          if (!file) {
            console.log(file, chunk)
          }
          return { 'autoUuid': this.autoUuid }
        },
        // query: { 'suffix': this.backgroundProfileParam.suffix },
        // 上传方式
        method: 'multipart',
        allowDuplicateUploads: true,
        // 用于格式化你想要剩余时间，一般可以用来做多语言
        parseTimeRemaining: function(timeRemaining, parsedTimeRemaining) {
          const time = parsedTimeRemaining
            .replace(/\syears?/, '年')
            .replace(/\days?/, '天')
            .replace(/\shours?/, '小时')
            .replace(/\sminutes?/, '分钟')
            .replace(/\sseconds?/, '秒')
          console.log('剩余时间: ', time)
          return time
        }
      },
      fileStatusText: {
        success: '上传成功',
        error: '上传失败',
        uploading: '上传中...',
        paused: '暂停',
        waiting: '等待中...',
        cmd5: 'cmd5'
      },
      backgroundProfileParam: {
        suffix: ACCEPT_CONFIG.getAll(),
        maxFileSize: 200
      },
      showErrorFileText: '',
      showSuccessFileText: '',
      autoUuid: crypto.randomUUID()
    }
  },
  created() {
    // 后台配置文件参数
    getVarParam().then(response => {
      this.backgroundProfileParam.suffix = ACCEPT_CONFIG.getAll()
      var suffix = response.data.document.toString() + ',' +
        response.data.image.toString() + ',' +
        response.data.media.toString() + ',' +
        response.data.text.toString()
      try {
        // 转大小写
        suffix = suffix.toLocaleUpperCase() + ',' + suffix.toLocaleLowerCase()
      } catch (e) {
        console.log(e)
      }
      this.backgroundProfileParam = { suffix: suffix, maxFileSize: response.data.maxFileSize[0] }
      if (suffix && !this.isEmpty(suffix)) {
        this.attrs.accept = []
        var tempSuffix = []
        suffix.split(',').forEach(item => {
          tempSuffix.push('.' + item)
        })
        this.attrs.accept = tempSuffix.join(',')
        this.$refs.uploadBtn.$el.querySelectorAll('input')[0].accept = tempSuffix.join(',')
      } else {
        this.attrs.accept = ACCEPT_CONFIG.getAll()
      }
    })
  },
  // mounted() {},
  methods: {
    onFileAdded: function() {
    // onFileAdded: function(file) {
    },
    onFilesAdded(files) {
      if (files !== undefined && files !== null && files.length > 0) {
        files.forEach(item => {
          this.checkFile(item)
        })
      }
    },
    // 上传中
    onFileProgress() {},
    // 上传完成
    successUpload(rootFile, file, message) {
      if (rootFile || file) {
        const objMessage = JSON.parse(message)
        if (objMessage.data !== null) {
          var color = objMessage.data.code === '200' ? 'green' : 'red'
          if (objMessage.data.code === '200') {
            this.showSuccessFileText += ('<span style=\'color:' + color + '\'>(' + objMessage.data.msg + ')</span>') + (file.relativePath === '' ? file.name : file.relativePath) + '<br>'
          } else {
            this.showErrorFileText += ('<span style=\'color:' + color + '\'>(' + objMessage.data.msg + ')</span>') + (file.relativePath === '' ? file.name : file.relativePath) + '<br>'
          }
        }
      }
    },
    errorUpload() {
      this.$message({
        type: 'warning',
        message: '上传失败',
        duration: 1000
      })
    },
    // 整个根文件上传结束
    fileComplete() {
      // fileComplete(rootFile) {
      this.autoUuid = crypto.randomUUID()
    },
    checkFile(file) {
      var fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1, file.name.length)
      var size
      try {
        size = parseInt(this.backgroundProfileParam.maxFileSize)
      } catch (e) {
        size = 200
        console.error('环境变量配置异常' + e)
      }
      if (file.size >= 1024 * 1024 * size) {
        this.showErrorFileText += ('<span style=\'color:red\'>(该文件文件大小上限)</span>') + (file.relativePath === '' ? file.name : file.relativePath) + '<br>'
        file.cancel()
        file.error = true
        return false
      }
      if (file.name.substring(0, 1) === '.') {
        console.log(' <span style="color:#000000">(跳过该文件)</span>' + (file.relativePath === '' ? file.name : file.relativePath) + '<br>')
        file.cancel()
        file.error = true
        return false
      }
      if (!this.backgroundProfileParam.suffix.includes(fileSuffix)) {
        this.showErrorFileText += ('<span style=\'color:#f3ab00\'>(不支持该类型文件上传)</span>') + (file.relativePath === '' ? file.name : file.relativePath) + '<br>'
        file.cancel()
        file.error = true
        return false
      }
      this.showSuccessFileText += ('<span style=\'color:#1a99cb\'>(合法!)</span>') + (file.relativePath === '' ? file.name : file.relativePath) + '<br>'
    }
  }
}
</script>

<style scoped>
.uploader-example {
  position: unset!important;
  width: 380px;
  height: 400px;
  max-height: 400px;
  z-index: 3000;
  bottom: 0;
  right: 0;
  background: #fff;
  padding: 0;
  border-radius: 0;
  box-shadow: 0 0 0 0 #ccc;
}
.uploader-drop {
  position: unset;
  padding: 0;
  overflow: auto;
  border: 0 dashed #ccc0;
  background-color: #f5f5f500;
  max-height: 400px;
}
.uploader-btn {
  display: inline-block;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  background: #fff;
  border: 1px solid #DCDFE6;
  color: #606266;
  -webkit-appearance: none;
  text-align: center;
  box-sizing: border-box;
  outline: none;
  margin: 0;
  transition: .1s;
  font-weight: 400;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  padding: 10px;
  width: 95px !important;
  height: 35px !important;
  font-size: 14px;
  border-radius: 4px;
}
</style>
